<template>
  <div>
    <div style="width: 100%; height: 100vh; background: #ffffff">
      <div ref="container" style="width: 100%; height: 100%"></div>
      <div
        v-if="contextMenu.visible"
        class="context-menu"
        :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
      >
        <div class="context-menu-item" @click.stop="addDep(0)">{{ $t('public.Adddepartment') }}</div>
        <div class="context-menu-item" v-if="currentModel.pid !== 0" @click.stop="addDep(1)">
          {{ $t('public.edit') }}
        </div>
        <div class="context-menu-item" v-if="currentModel.pid !== 0" @click.stop="addDep(2)">
          {{ $t('public.delete') }}
        </div>
      </div>
    </div>

    <rightRole
      ref="roleBox"
      :config="drawerConfig"
      :frame-id="frameId"
      :parent-id="parentId"
      :parent-tree="parentTree"
    />
  </div>
</template>
  
  <script>
import G6 from '@antv/g6'
import { configFrameDeleteApi } from '@/api/setting'

export default {
  components: {
    rightRole: () => import('./rightRole')
  },
  props: {
    parentTree: {
      type: Array,
      default: () => {
        return []
      }
    },
    frameId: {
      type: Number | String,
      default: () => {
        return 0
      }
    }
  },
  name: 'OrgChartFinalV2',
  data() {
    return {
      text: '新增部门',
      graph: null,
      selectedId: null,
      contextMenu: {
        visible: false,
        x: 0,
        y: 0,
        node: null,
        collapsed: false
      },
      currentModel: null,

      drawerConfig: {},
      filterText: '',
      isShowEdit: '',
      multipleSelection: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      frame_id: '',
      personConfig: {},
      parentId: [],
      topId: '', // 顶级id
      defaultFrame: [],
      activeValue: '' // 记录当前那个框展开
    }
  },
  mounted() {
    this.initGraph()
    document.addEventListener('click', this.hideContextMenu)
    // document.addEventListener("contextmenu", this.hideContextMenu);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.hideContextMenu)
    // document.removeEventListener("contextmenu", this.hideContextMenu);
    if (this.graph) {
      this.graph.destroy()
    }
  },
  methods: {
    initGraph() {
      const container = this.$refs.container
      const width = container.scrollWidth
      const height = container.scrollHeight || 800
      const _this = this

      // 注册自定义节点（保持完全一致）
      G6.registerNode('custom-node', {
        draw(cfg, group) {
          const titleLength = cfg.label ? cfg.label.length : 0
          const maxWidth = 300
          const charWidth = 15
          let mainWidth = Math.min(maxWidth, titleLength * charWidth + 30)
          let mainHeight = 40
          const labelFontSize = 14
          const padding = 10
          const lineHeight = 22
          const hasJobs = cfg.jobs && cfg.jobs.length > 0
          if (hasJobs) mainHeight += cfg.jobs.length * lineHeight

          const isSelected = cfg.value === _this.selectedId

          const keyShape = group.addShape('rect', {
            attrs: {
              width: mainWidth,
              height: mainHeight,
              x: -mainWidth / 2,
              y: -mainHeight / 2,
              radius: 6,
              stroke: isSelected ? '#ff4d4f' : _this.getNodeBorderColor(cfg),
              fill: isSelected ? '#fff1f0' : _this.getNodeFillColor(cfg),
              lineWidth: isSelected ? 3 : 1.5,
              shadowColor: '#e0e0e0',
              shadowBlur: 10,
              cursor: 'pointer'
            },
            name: 'main-box'
          })

          group.addShape('text', {
            attrs: {
              text: cfg.label,
              x: 0,
              y: -mainHeight / 2 + padding,
              textAlign: 'center',
              textBaseline: 'top',
              fontSize: labelFontSize,
              fontWeight: 'bold',
              fill: '#333',
              cursor: 'pointer',
              textOverflow: 'ellipsis',
              textWrap: 'wrap',
              width: mainWidth - padding * 2,
              maxLines: 1
            },
            name: 'title'
          })

          if (cfg.children && cfg.children.length > 0) {
            group.addShape('marker', {
              attrs: {
                x: 0,
                y: mainHeight / 2 + 6,
                r: 6,
                symbol: cfg.collapsed ? G6.Marker.expand : G6.Marker.collapse,
                stroke: '#666',
                fill: '#fff',
                cursor: 'pointer'
              },
              name: 'collapse-icon'
            })
          }

          return keyShape
        },
        afterUpdate(cfg, item) {
          const group = item.getContainer()
          const mainBox = group.find((ele) => ele.get('name') === 'main-box')
          if (mainBox) {
            const isSelected = cfg.value === _this.selectedId
            mainBox.attr({
              stroke: isSelected ? '#ff4d4f' : _this.getNodeBorderColor(cfg),
              fill: isSelected ? '#fff1f0' : _this.getNodeFillColor(cfg),
              lineWidth: isSelected ? 3 : 1.5
            })
          }
        },
        getAnchorPoints() {
          return [[0.5, 0]]
        }
      })
      // 注册自定义线条
      G6.registerEdge('flow-line', {
        draw(cfg, group) {
          const startPoint = cfg.startPoint
          const endPoint = cfg.endPoint
          console.log('startPoint', startPoint)
          console.log('endPoint', endPoint)

          const { style } = cfg
          const shape = group.addShape('path', {
            attrs: {
              stroke: style.stroke,
              endArrow: style.endArrow,
              path: [
                ['M', startPoint.x, startPoint.y],
                ['L', startPoint.x, (startPoint.y + endPoint.y) / 2],
                ['L', endPoint.x, (startPoint.y + endPoint.y) / 2],
                ['L', endPoint.x, endPoint.y]
              ]
            }
          })

          return shape
        }
      })
      // 初始化图表
      this.graph = new G6.TreeGraph({
        container,
        width,
        height,
        modes: {
          default: ['drag-canvas', 'zoom-canvas', 'drag-node']
        },
        defaultNode: {
          type: 'custom-node'
        },
        defaultEdge: {
          type: 'cubic-vertical',
          // type:'flow-line',
          style: {
            stroke: '#A3B1BF',
            lineWidth: 2
          }
        },
        layout: {
          type: 'compactBox',
          direction: 'V',
          getId: (d) => d.id, // 使用value作为唯一标识
          getHeight: () => 40, // 简化高度计算
          getWidth: () => 160,
          getVGap: () => 60,
          getHGap: () => -20
        }
      })

      const formatData = (data) => {
        const processNode = (node, depth = 0) => {
          return {
            id: node.value.toString(),
            depth: depth,
            ...node,
            children: node.children ? node.children.map((child) => processNode(child, depth + 1)) : []
          }
        }
        return processNode(data.data)
      }
      console.log('-------------------', this.parentTree[0])

      const formattedData = formatData({ data: this.parentTree[0] || {} })
      console.log('formattedData', formattedData)
      this.graph.data(formattedData)
      this.graph.render()
      this.graph.fitView()

      // 点击事件处理
      this.graph.on('node:click', (evt) => {
        const { item, target } = evt
        const model = item.getModel()
        const shapeName = target.get('name')
        if (shapeName === 'collapse-icon') {
          model.collapsed = !model.collapsed
          this.graph.updateItem(item, { collapsed: model.collapsed })
          this.graph.layout()
          // this.graph.focusItem(item);
        } else {
          this.selectedId = model.value
          this.graph.getNodes().forEach((node) => {
            this.graph.updateItem(node, {})
          })
          //   alert(`点击了节点：${model.label}`)
          this.$emit('childEvt', model)
        }
      })

      // 添加正确的右键事件监听
      this.graph.on('node:contextmenu', (evt) => {
        evt.preventDefault()
        const { item, originalEvent } = evt
        const model = item.getModel()

        console.log('todoing-model', model)
        // if (model.depth == 0) return

        // if (model.depth === 3) {
        //   this.text = '1111'
        // } else {
        //   this.text = '新增部门'
        // }

        this.contextMenu.visible = true
        this.contextMenu.x = originalEvent.clientX
        this.contextMenu.y = originalEvent.clientY
        this.contextMenu.node = item
        this.contextMenu.collapsed = model.collapsed
        // this.contextMenu = {
        //   visible: true,
        //   x: originalEvent.clientX,
        //   y: originalEvent.clientY,
        //   node: item,
        //   collapsed: model.collapsed,
        // };

        console.log('model', model)
        this.currentModel = model
        console.log('this.parentTree', this.parentTree)
        this.topId = this.parentTree.length ? this.parentTree[0].value : ''
        console.log('contextMenu', this.contextMenu)
      })

      window.addEventListener('resize', () => {
        if (!this.graph || this.graph.get('destroyed')) return
        this.graph.changeSize(container.scrollWidth, container.scrollHeight)
      })
    },

    // getNodeBorderColor(cfg) {
    //   if (cfg.value === 1) return "#FF8C00"; // 根据value判断根节点
    //   if (cfg.children) return "#1E90FF";
    //   return "#32CD32";
    // },

    // getNodeFillColor(cfg) {
    //   if (cfg.value === 1) return "#FFEB99";
    //   if (cfg.children) return "#E6F7FF";
    //   return "#F1F8E9";
    // },
    getNodeBorderColor(cfg) {
      const colors = this.getLevelColors()
      const depth = cfg.depth || 0
      return colors[Math.min(depth, colors.length - 1)].border
    },

    getNodeFillColor(cfg) {
      const colors = this.getLevelColors()
      const depth = cfg.depth || 0
      return colors[Math.min(depth, colors.length - 1)].fill
    },

    getLevelColors() {
      return [
        { border: '#FF8C00', fill: '#FFEB99' }, // 第0层（根节点）
        { border: '#1E90FF', fill: '#E6F7FF' }, // 第1层
        { border: '#32CD32', fill: '#F1F8E9' }, // 第2层
        { border: '#FF69B4', fill: '#FFB6C1' }, // 第3层
        { border: '#9932CC', fill: '#E6E6FA' } // 第4层
        // 可继续扩展更多层级...
      ]
    },

    // 新增右键菜单方法
    hideContextMenu() {
      this.contextMenu.visible = false
    },
    addDep(type) {
      if (this.contextMenu.node) {
        const model = this.contextMenu.node.getModel()
        console.log('model-----', model)
        this.hideContextMenu()

        switch (type) {
          case 0:
            this.addDivsion(0)
            break
          case 1:
            this.addDivsion(1)
            break
          case 2:
            this.hanleDelete(model)
            break
        }
      }
    },
    // 添加子部门
    addDivsion(type) {
      const node = this.currentModel
      console.log('node', node)
      // node.path.push(node.value)
      if (node.pid === 0) {
        // 顶级判断
        node.path = []
      }
      this.parentId = [...new Set(node.path)]

      if (!type) {
        //第一个按钮进来的
        this.parentId.push(node.value)
      }

      console.log('parentId', this.parentId)
      this.drawerConfig.title = type
        ? this.$t('setting.group.editorialdepartment')
        : this.$t('setting.group.adddepartment')
      this.drawerConfig.type = type
      this.drawerConfig.id = node.value
      this.drawerConfig.disabled = !!(this.topId === node.value && type)
      this.$refs.roleBox.handelOpen()
      this.$refs.roleBox.getDepartmentHead()
    },
    // 删除部门
    async hanleDelete(data) {
      await this.$modalSure('确定删除改部门吗')
      await configFrameDeleteApi(data.value)
      this.$bus.$emit('getList')
    }
  }
}
</script>
  <style>
.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  min-width: 120px;
}

.context-menu-item {
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: background 0.3s;
}

.context-menu-item:hover {
  background: #f5f5f5;
}

.context-menu-item:not(:last-child) {
  border-bottom: 1px solid #eee;
}
</style>
  